package ru.rchervot.sanasar.client.view;

import ru.rchervot.sanasar.client.event.EventPageChange;
import ru.rchervot.sanasar.client.event.EventSelectedNone;
import ru.rchervot.sanasar.client.event.EventSelectedSeveral;
import ru.rchervot.sanasar.client.event.EventUIResultsSplitChange;
import ru.rchervot.sanasar.client.event.HandlerPageChange;
import ru.rchervot.sanasar.client.event.HandlerSelectedNone;
import ru.rchervot.sanasar.client.event.HandlerSelectedSeveral;
import ru.rchervot.sanasar.client.model.SearchResultsItem;
import ru.rchervot.sanasar.client.place.Place;

import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.shared.HandlerManager;

public abstract class AbstractRecordHeaderPresenter implements RecordHeaderPresenter {
	
	private final HandlerManager eventBus;
	private final Display display;
	
	public AbstractRecordHeaderPresenter(Display display, HandlerManager eventBus) {
		this.eventBus = eventBus;
		this.display = display;
		
		listenForSelectedNone();
		listenForSelectedSeveral();
		listenForPageChange();
		
		addDoubleClickHandler();
  }
	
	@Override
	public void bindDisplay() {
		display.setPresenter(this);
	}
	
  @Override
	public Display getDisplay() {
		return display;
	}
  
  @Override
	public void go(Place place) {
		// TODO Auto-generated method stub
		
	}
  
  protected void listenForPageChange() {
		eventBus.addHandler(EventPageChange.getType(),
				new HandlerPageChange<SearchResultsItem>() {
			@Override
			public void onPageChange(EventPageChange<SearchResultsItem> event) {
				if (event.isStartPage()) {
					display.renderStartPage();
				} else {
					if (event.getPage().isEmpty()) {
						display.renderEmptyPage();
					} else {
						display.renderSelectedOne();
					}					
				}
			}
		});
	}
	
	protected void listenForSelectedNone() {
		eventBus.addHandler(EventSelectedNone.getType(),
				new HandlerSelectedNone() {
			@Override
			public void onAction(
					EventSelectedNone event) {
				display.renderSelectedNone();
			}
		});
	}
	
	protected void listenForSelectedSeveral() {
		eventBus.addHandler(EventSelectedSeveral.getType(),
				new HandlerSelectedSeveral() {
			@Override
			public void onAction(
					EventSelectedSeveral event) {
				display.renderSelectedSeveral();
			}
		});
	}
	
	protected void addDoubleClickHandler() {
		display.getBasePanel().addDoubleClickHandler(new DoubleClickHandler() {
			@Override
			public void onDoubleClick(DoubleClickEvent event) {
				eventBus.fireEvent(EventUIResultsSplitChange.buildExpandRight());
			}
		});
	}
}
